https://leetcode.com/problems/binary-tree-inorder-traversal/
中序排序法訪問順序為左節點->根節點->右節點。
利用遞迴的觀念,訪問左節點後直到為空,接續訪問根節點直到為空,最後訪問右節點。
void recursive(struct TreeNode* parent, int* recursiveResult, int* recursiveSize){
if(parent==NULL){
return;
}
if(parent->left==NULL && parent->right==NULL){
recursiveResult[*recursiveSize]=parent->val;
(*recursiveSize)++;
return;
}
if(parent->left!=NULL){
recursive(parent->left, recursiveResult, recursiveSize);
}
recursiveResult[*recursiveSize]=parent->val;
(*recursiveSize)++;
if(parent->right!=NULL){
recursive(parent->right, recursiveResult, recursiveSize);
}
return;
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int* traversalResult=(int*)malloc(1000*sizeof(struct TreeNode));
recursive(root, traversalResult, returnSize);
return traversalResult;
}
var inorderTraversal = function(root) {
const stack = [];
const res = [];
while (root || stack.length) {
if (root) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
res.push(root.val);
root = root.right;
}
}
return res;
};
Push() 將值放入陣列
Pop() 將值從陣列最後取出
https://github.com/SIAOYUCHEN/leetcode
https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136
本日分享:
Everyone who pursues a dream has a silent time, a day that only oneself knows, sometimes I spend a lot of effort and endure a lot of loneliness and loneliness.
每個追求夢想的人,都有一段沉默的時光, 一段只有自己知道的日子, 有時候,付出了很多努力,有時候也忍受了很多的孤獨和寂寞。